package com.shujia.jichu

import com.alibaba.fastjson.{JSON, JSONArray, JSONObject}

import scala.io.Source

object Demo21Json {
  def main(args: Array[String]): Unit = {
    //json: {"键":值}

    /**
     * 使用第三方的json解析工具：fastjson 或者 Gson
     */
    val stuList: List[String] = Source.fromFile("scala/data/stu2.json").getLines().toList
    val jsonStr: String = stuList.mkString("\n")
    //    println(jsonStr)

    //使用fastjson工具中的JSON类
    //    val jSONObject: JSONObject = JSON.parseObject(jsonStr)
    //    //通过json对象使用键获取值
    //    val address: String = jSONObject.getString("address")
    //    println(address)

    //[{"address":"安徽合肥","name":"张三","age":18},{"like":["踢足球","打篮球","举杠铃"],"name":"李四","age":18}]
    val jSONArray: JSONArray = JSON.parseArray(jsonStr)
    //    println(jSONArray)
    val secondJson: JSONObject = jSONArray.getJSONObject(1)
    val likes: String = secondJson.getString("like")
    val likesArray: Array[String] = likes.replaceAll("[\\[|\\]|\"]", "").split(",")
    likesArray.foreach(println)

    //    var index = 0
    //    while (index<jSONArray.size()){
    //      //通过索引下标获取每一个json串
    //      jSONArray.getJSONObject(index)
    //    }


  }
}
